﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;

namespace SUNRPA.CONTROLS.IMPL.controls {
    /// <summary>
    /// TODO: 1、等待下载完成超时
    /// </summary>
    public class Wait4WebEleNAction : BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            Wait4WebEleNParam? param = item.ControlParam as Wait4WebEleNParam;
            WebElement ele = param.WebEle as WebElement;
            //判断是否为web元素
            if(ele == null){ 
                throw new RpaRuntimeException("元素不是web元素，无法进行等待web元素操作");
            }
            string webObject = param.WebObj;
            WebPage webPage = this.GetObjVar<WebPage>(ref webObject, globleData);
            if(webPage == null){ 
                throw new RpaRuntimeException("网页为空，无法进行等待web元素操作");
            }
            
            int waitType = param.WaitType;

            bool canExpire = param.CanExpire;
            string expireTimeString = param.WaitExpireTime;
            this.GetStringVar(ref expireTimeString, globleData);
            int expireTime = int.Parse(expireTimeString);

            string waitEleResult = param.WaitEleResult;
            this.GetStringVar(ref waitEleResult, globleData);
            bool waitResult = false;
            BrowserUtil browserUtil;
            switch(webPage.Bt){ 
                case BrowserType.GOOGLE:
                    browserUtil = new ChromeUtil();
                    waitResult = browserUtil.WaitWebEle(waitType, canExpire, ele, webPage, expireTime);
                    break;
                case BrowserType.IE:
                    break;
                case BrowserType.EDGE:
                    break;
                default:
                    throw new RpaRuntimeException("浏览器类型错误");
            }
            this.saveVar(globleData, waitEleResult, new BoolModel(waitEleResult, waitResult), DefaultContents.RUNNING_PARAM);
            return currentIndex;
        }
    }
}
